<template>
  <div :class="className" :style="{height:height,width:width}"/>
</template>

<script>
  import echarts from 'echarts'

  const animationDuration = 6000

  export default {
    props: {
      className: {
        type: String,
        default: 'chart'
      },
      width: {
        type: String,
        default: '100%'
      },
      height: {
        type: String,
        default: '395px'
      }
    },
    data() {
      return {
        option: {
          xAxis: {
            max: 'dataMax',
          },
          yAxis: {
            type: 'category',
            data: ['初意', '白度', '叮咚', '滴答', '哎呀'],
            inverse: true,
            animationDuration: 300,
            animationDurationUpdate: 300,
            max: 2 // only the largest 3 bars will be displayed
          },
          series: [{
            realtimeSort: true,
            name: '热度',
            type: 'bar',
            data: this.data,
            label: {
              show: true,
              position: 'right',
              valueAnimation: true
            }
          }],
          legend: {
            show: true
          },
          animationDuration: 0,
          animationDurationUpdate: 3000,
          animationEasing: 'linear',
          animationEasingUpdate: 'linear'
        },
        data: [],
      }
    },
    mounted() {
      this.$nextTick(() => {
        for (let i = 0; i < 5; ++i) {
          this.data.push(Math.round(Math.random() * 200));
        }
        if (this.data) {
          this.option.series[0].data = this.data
        } else {
          return;
        }
        setTimeout(() => {
          this.run()
        },0)
        setInterval(() => {
          this.run()
        },3000)
      })
    },
    beforeDestroy() {
      if (!this.chart) {
        return
      }
      this.chart.dispose()
      this.chart = null
    },
    methods: {
      initChart() {
        this.chart = echarts.init(this.$el, 'macarons')
        this.chart.setOption(this.option)
      },

      run() {
        let data = this.option.series[0].data;
        if (data.length !== undefined) {
          for (let i = 0; i < data.length; ++i) {
            if (Math.random() > 0.9) {
              data[i] += Math.round(Math.random() * 2000);
            } else {
              data[i] += Math.round(Math.random() * 200);
            }
          }
          this.initChart()
        }
      },


    }
  }
</script>
